package com.fangfang.home;

import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.common.base.fragment.BaseFragment;
import com.common.bean.InfoResult;
import com.common.image.ImagePreview;
import com.common.image.bean.ImageInfo;
import com.common.image.view.listener.OnBigImageClickListener;
import com.common.image.view.listener.OnBigImageLongClickListener;
import com.common.image.view.listener.OnBigImagePageChangeListener;
import com.common.image.view.listener.OnOriginProgressListener;
import com.common.net.EasyHttp;
import com.common.net.callback.SimpleCallBack;
import com.common.net.exception.ApiException;
import com.common.utils.GsonUtils;
import com.common.utils.ItemClickSupport;
import com.fangfang.R;
import com.fangfang.bean.home.ContentBean;
import com.fangfang.bean.home.FollowCardBean;
import com.fangfang.bean.home.HeaderBean;
import com.fangfang.bean.home.ItemListBean;
import com.fangfang.bean.home.PictureFollowCardBean;
import com.fangfang.bean.home.SquareCardCollectionBean;
import com.fangfang.bean.home.TextCardBean;
import com.fangfang.bean.home.VideoSmallCardBean;
import com.fangfang.home.adapter.DailyPaperAdapter;
import com.fangfang.utils.AddressApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;

/**
 * 日报
 */
public class DailyPaperFragment extends BaseFragment {

    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    private String nextPageUrl = "";
    private List<ItemListBean> infos;
    private LinearLayoutManager linearLayoutManager;
    private DailyPaperAdapter dailyPaperAdapter;
    ImagePreview.LoadStrategy loadStrategy = ImagePreview.LoadStrategy.Default;
    private List<ImageInfo> imageInfoList = new ArrayList<>();

    public static DailyPaperFragment newInstance() {
        return new DailyPaperFragment();
    }

    @Override
    public boolean isImmersionBarEnabled() {
        return false;
    }

    @Override
    public View isSupportLoadSirEnabled() {
        return null;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_dai_paper;
    }

    @Override
    public void init() {
        linearLayoutManager = new LinearLayoutManager(getActivity());
        dailyPaperAdapter = new DailyPaperAdapter(getActivity(),infos);
        recycleView.setLayoutManager(linearLayoutManager);
        recycleView.setAdapter(dailyPaperAdapter);
        //单击
        ItemClickSupport.addTo(recycleView)
                .setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                    @Override
                    public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                        if(infos.get(position).getType().equals("pictureFollowCard")){
                            if(infos.get(position).getPictureFollowCard().getContent().getUrls()!=null){
                                if(imageInfoList!=null && imageInfoList.size()>0){
                                    imageInfoList.clear();
                                }
                                for (String image : infos.get(position).getPictureFollowCard().getContent().getUrls()) {
                                    ImageInfo imageInfo = new ImageInfo();
                                    // 原图地址
                                    imageInfo.setOriginUrl(image);
                                    // 缩略图；实际使用中，根据需求传入缩略图路径。如果没有缩略图url，可以将两项设置为一样。
                                    imageInfo.setThumbnailUrl(image.concat("-400"));
                                    imageInfoList.add(imageInfo);
                                }
                                lookPic();
                            }
                        }
                    }
                });
        //长按
        ItemClickSupport.addTo(recycleView).setOnItemLongClickListener(new ItemClickSupport.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClicked(RecyclerView recyclerView, int position, View v) {
                return false;
            }
        });
    }

    @Override
    public void loadData() {
        EasyHttp.get(AddressApi.dailypaper)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(String s) {
                        parseJson(s);
                    }
                });
    }

    @Override
    protected void onSuccess(int what, InfoResult t) {

    }

    @Override
    protected void onFail(int what, InfoResult t) {

    }

    /**
     * 解析数据
     *
     * @param s json字符串
     */
    private void parseJson(String s) {
        if (!TextUtils.isEmpty(s)) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                nextPageUrl = jsonObject.optString("nextPageUrl", "");
                JSONArray itemList = jsonObject.optJSONArray("itemList");
                String txt = itemList.toString();
                infos = GsonUtils.getInstance().jsonToList(jsonObject.optString("itemList"), ItemListBean.class);
                if (itemList != null) {
                    for (int i = 0; i < itemList.length(); i++) {
                        JSONObject ccurrentObject = itemList.getJSONObject(i);
                        switch (ccurrentObject.optString("type")) {
                            case "squareCardCollection":
                                SquareCardCollectionBean squareCardCollectionBean =
                                        GsonUtils.getInstance().jsonToClass(
                                                ccurrentObject.toString(),
                                                SquareCardCollectionBean.class);
                            case "textCard":
                                String textCard = ccurrentObject.optString("data");
                                TextCardBean textCardBean = GsonUtils.getInstance().jsonToClass(textCard,TextCardBean.class);
                                infos.get(i).setTextCardBean(textCardBean);
                                break;
                            case "videoSmallCard":
                                VideoSmallCardBean videoSmallCardBean = GsonUtils.getInstance().jsonToClass(
                                        ccurrentObject.toString(),
                                        VideoSmallCardBean.class);
                                break;
                            case "followCard":
                                FollowCardBean followCardBean = new FollowCardBean();
                                String followCardBeanTxt = ccurrentObject.optString("data");
                                JSONObject objectfollowCardBean = new JSONObject(followCardBeanTxt);
                                String headerTxtfollowCardBean = objectfollowCardBean.optString("header");
                                HeaderBean headerBeanFC = GsonUtils.getInstance().jsonToClass(headerTxtfollowCardBean,HeaderBean.class);
                                followCardBean.setHeader(headerBeanFC);
                                String contentTxtPC = objectfollowCardBean.optString("content");
                                JSONObject objectContentPC = new JSONObject(contentTxtPC);
                                String contentDataPC = objectContentPC.optString("data");
                                ContentBean contentBeanPC = GsonUtils.getInstance().jsonToClass(contentDataPC,ContentBean.class);
                                followCardBean.setContent(contentBeanPC);
                                infos.get(i).setFollowCardBean(followCardBean);
                                break;
                            case "pictureFollowCard":
                                PictureFollowCardBean pictureFollowCard = new PictureFollowCardBean();
                                String picTxt = ccurrentObject.optString("data");
                                JSONObject objectPic = new JSONObject(picTxt);
                                String headerTxt = objectPic.optString("header");
                                HeaderBean headerBean = GsonUtils.getInstance().jsonToClass(headerTxt,HeaderBean.class);
                                pictureFollowCard.setHeader(headerBean);
                                String contentTxt = objectPic.optString("content");
                                JSONObject objectContent = new JSONObject(contentTxt);
                                String contentData = objectContent.optString("data");
                                ContentBean contentBean = GsonUtils.getInstance().jsonToClass(contentData,ContentBean.class);
                                pictureFollowCard.setContent(contentBean);
                                infos.get(i).setPictureFollowCard(pictureFollowCard);
                                break;
                            default:
                                break;
                        }
                    }
                }
                setDatas();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void setDatas() {
        dailyPaperAdapter.setDataSource(infos);
    }

    private void lookPic(){
        ImagePreview.getInstance()
                // 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好
                .setContext(getActivity())
                // 从第几张图片开始，索引从0开始哦~
                .setIndex(0)
                //=================================================================================================
                // 有三种设置数据集合的方式，根据自己的需求进行三选一：
                // 1：第一步生成的imageInfo List
                .setImageInfoList(imageInfoList)
                // 2：直接传url List
                //.setImageList(List<String> imageList)
                // 3：只有一张图片的情况，可以直接传入这张图片的url
                //.setImage(String image)
                //=================================================================================================
                // 加载策略，默认为手动模式
                .setLoadStrategy(loadStrategy)
                // 保存的文件夹名称，会在Picture目录进行文件夹的新建。比如："BigImageView"，会在Picture目录新建BigImageView文件夹)
                .setFolderName("BigImageView")
                // 缩放动画时长，单位ms
                .setZoomTransitionDuration(300)
                // 是否启用点击图片关闭。默认启用
                .setEnableClickClose(true)
                // 是否启用下拉关闭。默认不启用
                .setEnableDragClose(true)
                // 是否启用上拉关闭。默认不启用
                .setEnableUpDragClose(true)
                // 是否显示关闭页面按钮，在页面左下角。默认不显示
                .setShowCloseButton(true)
                // 设置关闭按钮图片资源，可不填，默认为库中自带：R.drawable.ic_action_close
                .setCloseIconResId(R.drawable.ic_action_close)
                // 是否显示下载按钮，在页面右下角。默认显示
                .setShowDownButton(true)
                // 设置下载按钮图片资源，可不填，默认为库中自带：R.drawable.icon_download_new
                .setDownIconResId(R.drawable.icon_download_new)
                // 设置是否显示顶部的指示器（1/9）默认显示
                .setShowIndicator(true)
                // 设置失败时的占位图，默认为库中自带R.drawable.load_failed，设置为 0 时不显示
                .setErrorPlaceHolder(R.drawable.load_failed)
                // 点击回调
                .setBigImageClickListener(new OnBigImageClickListener() {
                    @Override
                    public void onClick(View view, int position) {

                    }
                })
                // 长按回调
                .setBigImageLongClickListener(new OnBigImageLongClickListener() {
                    @Override
                    public boolean onLongClick(View view, int position) {
                        return false;
                    }
                })
                // 页面切换回调
                .setBigImagePageChangeListener(new OnBigImagePageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    }

                    @Override public void onPageSelected(int position) {
                    }

                    @Override public void onPageScrollStateChanged(int state) {
                    }
                })

                //=================================================================================================
                // 设置查看原图时的百分比样式：库中带有一个样式：ImagePreview.PROGRESS_THEME_CIRCLE_TEXT，使用如下：
                .setProgressLayoutId(ImagePreview.PROGRESS_THEME_CIRCLE_TEXT, new OnOriginProgressListener() {
                    @Override public void progress(View parentView, int progress) {
                        // 需要找到进度控件并设置百分比，回调中的parentView即传入的布局的根View，可通过parentView找到控件：
                        ProgressBar progressBar = parentView.findViewById(R.id.sh_progress_view);
                        TextView textView = parentView.findViewById(R.id.sh_progress_text);
                        progressBar.setProgress(progress);
                        String progressText = progress + "%";
                        textView.setText(progressText);
                    }

                    @Override public void finish(View parentView) {

                    }
                })

                // 使用自定义百分比样式，传入自己的布局，并设置回调，再根据parentView找到进度控件进行百分比的设置：
                //.setProgressLayoutId(R.layout.image_progress_layout_theme_1, new OnOriginProgressListener() {
                //    @Override public void progress(View parentView, int progress) {
                //        Log.d(TAG, "progress: " + progress);
                //
                //        ProgressBar progressBar = parentView.findViewById(R.id.progress_horizontal);
                //        progressBar.setProgress(progress);
                //    }
                //
                //    @Override public void finish(View parentView) {
                //        Log.d(TAG, "finish: ");
                //    }
                //})
                //=================================================================================================
                // 开启预览
                .start();
    }
}
